<template>
  <div class="login">
    <div class="login-box">
      <h2>梦学谷会员管理系统</h2>
      <myinput msg="账号" :fromObj="loginfrom" datakey="username" verify="usernameflag" verifymsg="账号格式不正确" />
      <myinput msg="密码" :fromObj="loginfrom" datakey="password" verify="passwordflag" verifymsg="密码格式不正确" />
      <mybutton @click="login" />
    </div>
  </div>
</template>

<script>
import mybutton from "../components/fromclass/mybutton"; //button 组件
import myinput from "../components/fromclass/myinput"; //input 组件
import api from "../axios/api/api"; //封装axios请求
export default {
  components: {
    mybutton,
    myinput,
  },
  data() {
    return {
      loginfrom: {
        username: "", //用户名
        password: "", //密码
        usernameflag: false, //用户名判断flag 控制input框下的字体
        passwordflag: false, //密码flag 控制密码
      },
    };
  },
  beforeMount() {
    if (localStorage.getItem("token")) {
      this.$router.push("/leteuser");
    }
  },
  methods: {
    login() {
      // 登录验证阶段
      var flag = false;
      var userEz = /^[0-9A-Za-z]{3,}$/;
      if (
        !userEz.test(this.loginfrom.username) ||
        this.loginfrom.username == ""
      ) {
        this.loginfrom.usernameflag = true;
        flag = true;
      } else {
        this.loginfrom.usernameflag = false;
      }

      if (
        !userEz.test(this.loginfrom.password) ||
        this.loginfrom.password == ""
      ) {
        this.loginfrom.passwordflag = true;
        flag = true;
      } else {
        this.loginfrom.passwordflag = false;
      }
      if (flag) {
        return;
      }
      var username = this.loginfrom.username;
      var password = this.loginfrom.password;
      //登录成功进入首页

      api.loginin({ username, password }).then((data) => {
        // 验证登录成功跳转页面
        if (data.data.code === 2000) {
          // element 按需引入组件
          this.$notify({
            title: "成功",
            message: data.data.message,
            type: "success",
          });
          // 登录成功存储token
          localStorage.setItem("token", data.data.data.token);
          this.$router.push("/leteuser");
        } else {
          this.$notify({
            title: "成功",
            message: "这是一条成功的提示消息",
            type: "success",
          });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100%;
  background-color: rgba(102, 102, 102, 0.137);
  .login-box {
    width: 400px;
    padding: 30px 20px;
    background-color: rgba(255, 255, 255, 0.315);
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    border-radius: 20px;
    position: relative;
    box-shadow: 1px 1px 15px 5px #ccc;
    h2 {
      text-align: center;
    }
    .mybutton {
      margin: 10px 65px;
    }
  }
}
</style>